#include "switch_driver.h"
#include "stm32f2xx.h"


#define BITGPIOA(x) (PIN_##x&GPIOA->IDR)
#define BITGPIOB(x) (PIN_##x&GPIOB->IDR)
#define BITGPIOC(x) (PIN_##x&GPIOC->IDR)
#define BITGPIOE(x) (PIN_##x&GPIOE->IDR)

#define PIN_TRIM_RH_R GPIO_Pin_13   ///<PC.13
#define PIN_TRIM_RH_L GPIO_Pin_1    ///< PC.01
#define PIN_TRIM_RV_U GPIO_Pin_2    ///< PC.02
#define PIN_TRIM_RV_D GPIO_Pin_3    ///< PC.03
#define PIN_TRIM_LV_U GPIO_Pin_5    ///< PE.05
#define PIN_TRIM_LV_D GPIO_Pin_6    ///< PE.06
#define PIN_TRIM_LH_R GPIO_Pin_3    ///< PE.03
#define PIN_TRIM_LH_L GPIO_Pin_4    ///< PE.04

#define TRIM_RH_R (!BITGPIOC(TRIM_RH_R))
#define TRIM_RH_L (!BITGPIOC(TRIM_RH_L))
#define TRIM_RV_U (!BITGPIOC(TRIM_RV_U))
#define TRIM_RV_D (!BITGPIOC(TRIM_RV_D))
#define TRIM_LV_U (!BITGPIOE(TRIM_LV_U ))
#define TRIM_LV_D (!BITGPIOE(TRIM_LV_D))
#define TRIM_LH_R (!BITGPIOE(TRIM_LH_R))
#define TRIM_LH_L (!BITGPIOE(TRIM_LH_L))


int trim_open(Driver *driver)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_AHB1PeriphClockCmd(RCC_AHB1ENR_GPIOCEN, ENABLE);
    RCC_AHB1PeriphClockCmd(RCC_AHB1ENR_GPIOEEN, ENABLE);

    /// PC: 4
    GPIO_InitStructure.GPIO_Pin =PIN_TRIM_RH_R | PIN_TRIM_RH_L | PIN_TRIM_RV_U | PIN_TRIM_RV_D;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
    
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    /// PE: 13
    GPIO_InitStructure.GPIO_Pin =PIN_TRIM_LV_U | PIN_TRIM_LV_D | PIN_TRIM_LH_R | PIN_TRIM_LH_L;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
    
    GPIO_Init(GPIOE, &GPIO_InitStructure);

    return 0;
}

int trim_write(Driver *driver, void *buffer, int len, OFFSET offset)
{
    return 0;
}

int trim_read(Driver *driver, void *buffer, int len, OFFSET offset)
{
    int t_int;
    char *p_char;

    if(len >8) len=8;

    p_char =(char*)buffer;
    for(t_int =0; t_int<len; t_int++)
    {
        switch(t_int)
        {
        case 0: *p_char++ =TRIM_LH_L? 1:0; break;
        case 1: *p_char++ =TRIM_LH_R? 1:0; break;
        case 2: *p_char++ =TRIM_LV_U? 1:0; break;
        case 3: *p_char++ =TRIM_LV_D? 1:0; break;
        case 4: *p_char++ =TRIM_RV_U? 1:0; break;
        case 5: *p_char++ =TRIM_RV_D? 1:0; break;
        case 6: *p_char++ =TRIM_RH_L? 1:0; break;
        case 7: *p_char++ =TRIM_RH_R? 1:0; break;
        }
    }

    return t_int;
}

int trim_io_control(Driver *driver, int io_type, int data)
{
    return 0;
}

int trim_close(Driver *driver)
{
    return 0;
}




Driver trim_driver=
{
    &trim_open,
    &trim_write,
    &trim_read,
    &trim_io_control,
    &trim_close
};

